package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public void deleteById(Long id) {
        try {
            //
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            //
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            //
            Hotel hotel = getById(id);
            HotelDoc hotelDoc = new HotelDoc(hotel);

            //
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            //
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            //
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult search(RequestParams params) {
        //创建Requset对象
        SearchRequest request = new SearchRequest("hotel");
        //
        SearchSourceBuilder source = request.source();
        Integer page = params.getPage();
        Integer size = params.getSize();
        source.from((page - 1) * size);
        source.size(size);
        //
        booleanQuery(source, params);
        //调用client执行
        List<HotelDoc> list = new ArrayList<>();
        try {

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long value = hits.getTotalHits().value;
            for (SearchHit hit : hits) {

                String docJson = hit.getSourceAsString();

                HotelDoc hotelDoc = JSON.parseObject(docJson, HotelDoc.class);

                Map<String, HighlightField> highlightFields = hit.getHighlightFields();


                //得到sort排序字段的值
                Object[] sortValues = hit.getSortValues();
                if (sortValues != null && sortValues.length > 0) {

                    //设置距离
                    hotelDoc.setDistance(sortValues[0]);

                }
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField != null) {
                        String name = highlightField.getFragments()[0].string();
                        hotelDoc.setName(name);
                    }
                }

                list.add(hotelDoc);
            }
            return new PageResult(value, list);
        } catch (IOException e) {
            e.printStackTrace();

            throw new RuntimeException();

        }
    }

    @Override
    public Map<String, List<String>> searchGetFilters(RequestParams params) {
        try {
            // 创建请求对象sour
            SearchRequest request = new SearchRequest("hotel");
            // 设置size
            request.source().size(0);

            SearchSourceBuilder source = request.source();
            // 聚合条件
            buildAggregation(source);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据聚合名称获取聚合结果

            // 4.2.获取buckets
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            List<String> cityAgg = getAggByName(aggregations, "cityAgg");
            List<String> starAgg = getAggByName(aggregations, "starAgg");
            result.put("brand", brandAgg);
            result.put("city", cityAgg);
            result.put("starName", starAgg);

            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    @Override
    public List<String> serchGetSuggestions(String prefix) {

        SearchRequest request = new SearchRequest("hotel");

        request.source().suggest(
                new SuggestBuilder().addSuggestion(
                        "mySuggestion",
                        SuggestBuilders
                                .completionSuggestion("suggestion")
                                .prefix(prefix)
                                .skipDuplicates(true)
                                .size(10)
                )
        );


        //
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            Suggest suggest = response.getSuggest();
            // 获取名称获取全结果
            CompletionSuggestion completionSuggester = suggest.getSuggestion("mySuggestion");
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : completionSuggester.getOptions()) {
                String string = option.getText().string();
                list.add(string);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 根据聚合名称获取聚合结果
        Terms aggTerms = aggregations.get(aggName);
        // 获取buckets
        List<? extends Terms.Bucket> buckets = aggTerms.getBuckets();
        List<String> brandList = new ArrayList<>();

        for (Terms.Bucket bucket : buckets) {
            // 获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }


    /**
     * @param source
     */
    private void buildAggregation(SearchSourceBuilder source) {

        source.aggregation(
                AggregationBuilders
                        .terms("brandAgg")
                        .field("brand")
                        .size(20)
        );

        source.aggregation(
                AggregationBuilders
                        .terms("cityAgg")
                        .field("city")
                        .size(50)
        );
        source.aggregation(
                AggregationBuilders
                        .terms("starAgg")
                        .field("starName")
                        .size(40)
        );


    }


    private void booleanQuery(SearchSourceBuilder source, RequestParams params) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        String key = params.getKey();
        // 构造关键词 key match搜索 must算分
        if (StringUtils.isNotBlank(key)) {
            //
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));

            source.highlighter(new HighlightBuilder().field("name")
                    .requireFieldMatch(false));
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        // 1.1 构建城市city term搜索
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }
        // 1,2 构建brand品牌搜索 term搜索 filter

        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 1.3 构建星级 starName term搜索 filter
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }
        // 1.5 价格范围
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery(
                    "price").gte(minPrice).lt(maxPrice));
        }
        //2 附近的酒店
        String location = params.getLocation();
        //判断是否传入位置
        if (StringUtils.isNotBlank(location)) {
            //按照距离排序
            source.sort(
                    SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS)
            );
        }

        /**
         *
         */
        String sortBy = params.getSortBy();
        if (StringUtils.isNotBlank(sortBy)) {
            if (sortBy.equals("score")) {
                source.sort(sortBy, SortOrder.DESC);
            } else if (sortBy.equals("price")) {
                source.sort(sortBy, SortOrder.ASC);
            }
        }


        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQueryBuilder,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });

        source.query(functionScoreQuery);
    }
}
